/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sg.edu.nus.iss.pacman.net.webservice;

import java.rmi.RemoteException;
import sg.edu.nus.iss.pacman.dao.UserProfile;
import sg.edu.nus.iss.pacman.net.URLConstants;
import sg.edu.nus.iss.pacman.util.WSUtils;

/**
 * A WebService client.
 * @author fredy
 */
public class WebServiceClient
{
    private WebServiceClientListener listener;
    private PacManWebServiceService_Stub stub;

    /**
     * Creates a new instance of WebServiceClient.
     * @param serverURL the server URL
     * @param listener the WebServiceClientListener
     */
    public WebServiceClient(String serverURL, WebServiceClientListener listener)
    {
        this.listener = listener;
        this.stub = new PacManWebServiceService_Stub(serverURL + URLConstants.WEB_SERVICE_URL);
    }

    /**
     * Adds user profile.
     * @param userProfile the user profile
     */
    public void addUserProfile(UserProfile userProfile)
    {
        Thread t = new Thread(new UserProfileWebServiceClientRunnable(userProfile));
        t.start();
    }

    class UserProfileWebServiceClientRunnable implements Runnable
    {
        private UserProfile userProfile;

        public UserProfileWebServiceClientRunnable(UserProfile userProfile)
        {
            this.userProfile = userProfile;
        }

        public void run()
        {
            try
            {
                stub.addUserProfile(WSUtils.convertUserProfileToUserProfileWS(userProfile));
                listener.userProfileUploaded();
            }
            catch (RemoteException ex)
            {
                ex.printStackTrace();
                throw new RuntimeException(ex.getMessage());
            }
        }
    }

    /**
     * Retrieves the map listing.
     */
    public void retrieveMapListing()
    {
        Thread t = new Thread(new RetrieveMapWebServiceClientRunnable());
        t.start();
    }

    class RetrieveMapWebServiceClientRunnable implements Runnable
    {
        public void run()
        {
            try
            {
                String[] mapNames = stub.getMapListing();
                listener.mapListingRetrieved(mapNames);
            }
            catch (RemoteException ex)
            {
                ex.printStackTrace();
                throw new RuntimeException(ex.getMessage());
            }
        }
    }
}
